import { HttpException, Injectable } from '@nestjs/common';
import { CreateRoleDto } from './dto/create-role.dto';
import { UpdateRoleDto } from './dto/update-role.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { Role } from './entities/role.entity';
import { In, Repository } from 'typeorm';
import { PaginationService } from '../../common/pagination/pagination.service';

@Injectable()
export class RoleService {
  constructor(
    @InjectRepository(Role) private readonly roleRepository: Repository<Role>,
    private pageService: PaginationService<Role>,
  ) {
    this.pageService = new PaginationService<Role>(this.roleRepository);
  }

  async create(createRoleDto: CreateRoleDto) {
    const data = this.roleRepository.create(createRoleDto);
    return await this.roleRepository.save(data);
  }

  async findAll(params: { page: number; pageSize: number }) {
    const res = await this.pageService.paginate({
      ...params,
      options: {
        relations: { permissions: true },
      },
    });
    return res;
  }

  // 分页查询
  async pageSearch(params: {
    page: number;
    pageSize: number;
    name: string;
    code: string;
  }) {
    const { page, pageSize, name, code } = params;
    // 定义查询构造器
    const qb = this.roleRepository.createQueryBuilder();
    // 模糊查询name、code
    name && qb.andWhere('name like :name', { name: `%${name}%` });
    code && qb.andWhere('code like :code', { code: `%${code}%` });
    // 连表查询
    qb.relation('permissions');
    // console.log('pageSearch params', params);
    // 分页查询
    return this.pageService.pageSearch({
      page,
      pageSize,
      queryBuilder: qb,
    });
  }

  async findOne(id: string) {
    return await this.roleRepository.findOne({
      where: { id },
      relations: { permissions: true },
    });
  }

  async findRolesByIds(roleIds: string[]) {
    return this.roleRepository.find({
      where: {
        id: In(roleIds),
      },
      relations: {
        permissions: true,
      },
    });
  }

  async update(id: string, updateRoleDto: UpdateRoleDto) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    const updateData = this.roleRepository.merge(data, updateRoleDto);
    return await this.roleRepository.save(updateData);
  }

  async remove(id: string) {
    const data = await this.findOne(id);
    if (!data) throw new HttpException('数据不存在', 400);
    return await this.roleRepository.delete({ id });
  }
}
